package com.xhj.bigfactory.bigFactory.Lock;

import java.util.concurrent.atomic.AtomicReference;
/**
 * -
 *
 * @author 见见 pure_xhj@163.com @Date 2021-07-26 @Time 10:13
 */
public class SpinLockDemo {
  AtomicReference<Thread> atomicReference = new AtomicReference<>();

  public void lock() {
    int i = 0;
    while (!atomicReference.compareAndSet(null, new Thread())) {
      i++;
    }
    System.out.println("i=" + i);
  }

  public void unlock() {
    atomicReference.compareAndSet(atomicReference.get(), null);
    //		while(!atomicReference.compareAndSet(atomicReference.get(),null)){}
  }

  public static void main(String[] args) {
    SpinLockDemo lock = new SpinLockDemo();
    new Thread(
            () -> {
              System.out.println(Thread.currentThread().getName() + " come in...");
              lock.lock();
              try {
                System.out.println("AAA do//");
                try {
                  Thread.sleep(1000);
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
              } catch (Exception e) {
                e.printStackTrace();
              } finally {
                lock.unlock();
              }
            },
            "AAA")
        .start();
    new Thread(
            () -> {
              System.out.println(Thread.currentThread().getName() + " come in...");
              lock.lock();
              try {
                System.out.println("BBB do//");
              } catch (Exception e) {
                e.printStackTrace();
              } finally {
                lock.unlock();
              }
            },
            "BBB")
        .start();
  }
}
